package com.flower.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.flower.domain.entity.BackageUser;
import com.flower.domain.entity.LoginUser;
import com.flower.mapper.BackageUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Objects;

@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private BackageUserMapper backageUserMapper;
    @Resource
    PasswordEncoder passwordEncoder;

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<BackageUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BackageUser::getName,username);
        BackageUser backageUser = backageUserMapper.selectOne(wrapper);
//        backageUser.setPassword(passwordEncoder.encode(backageUser.getPassword()));
        log.warn("加密过后的密码是:{}", passwordEncoder.encode("123456"));
        //如果查询不到数据就通过抛出异常来给出提示
        if(Objects.isNull(backageUser)){
            throw new RuntimeException("用户名或密码错误");
        }
        //TODO 根据用户查询权限信息 添加到LoginUser中
        //封装成UserDetails对象返回
        return new LoginUser(backageUser);
    }
}
